package com.sky.wsp.mybatis.plus.interceptor;

import com.sky.wsp.mybatis.plus.utils.SecurityContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义拦截器，从请求token中获取租户id，放到会话context中
 *
 * @author wangshaopeng@talkweb.com.cn
 * @Date 2023-01-11
 */
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // TODO 改为从请求token中获取
        String tenantIdStr = request.getParameter("tenantId");
        Long tenantId;
        if (null == tenantIdStr) {
            tenantId = 1L;
        } else {
            tenantId = Long.valueOf(tenantIdStr);
        }

        // TODO 改为从请求token中获取
        String userIdStr = request.getParameter("userId");
        Long userId;
        if (null == userIdStr) {
            userId = 1L;
        } else {
            userId = Long.valueOf(userIdStr);
        }

        // TODO 改为根据username，获取对应的组织机构数据权限
        List<Long> orgIds = new ArrayList<>();
        orgIds.add(4L);
        orgIds.add(5L);
        orgIds.add(6L);

        UserSessionVO vo = new UserSessionVO();
        vo.setTenantId(tenantId);
        vo.setUserId(userId);
        vo.setUsername(userId + "");
        vo.setOrgIds(orgIds);
        SecurityContextHolder.set(vo);


        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        SecurityContextHolder.remove();
    }
}
